﻿import { Component, OnInit, Injector, ViewEncapsulation, ElementRef, ViewChild } from '@angular/core';
import { AppComponentBase } from '@shared/common/app-component-base';
import { TreeStructureServiceProxy } from '@shared/service-proxies/service-proxies';
import { appModuleAnimation } from '@shared/animations/routerTransition';
import { ListResultDtoOfTreeNodeListDto } from '@shared/service-proxies/service-proxies';
import { TreeNode } from 'primeng/api';
import { TreeDataHelperService } from '@shared/utils/tree-data-helper.service';
import { ArrayToTreeConverterService } from '@shared/utils/array-to-tree-converter.service';

@Component({
    templateUrl: './tree-base.component.html',
    encapsulation: ViewEncapsulation.None,
    animations: [appModuleAnimation()]
})
export class TreeBaseComponent extends AppComponentBase implements OnInit {
    constructor(
        injector: Injector,
        private _treeService: TreeStructureServiceProxy,
        private _arrayToTreeConverterService: ArrayToTreeConverterService
    ) {
        super(injector);
    }

    selectedDate = new Date();

    treeData;

    treeMappings;

    ngOnInit(): void {
        this.treeMappings = [
            {
                target: 'label',
                targetFunction(item) {
                    return item.nodeName;
                }
            },
            {
                target: 'code',
                targetFunction(item) {
                    return item.nodeCode;
                }
            },
            {
                target: 'leaf',
                targetFunction(item) {
                    return false;
                }
            },
            {
                target: 'expandedIcon',
                value: 'fa fa-cog m--font-warning'
            },
            {
                target: 'collapsedIcon',
                value: 'fa fa-cog m--font-warning'
            },
            {
                target: 'selectable',
                value: true
            }
        ];
        this._treeService.getChildren(undefined).subscribe((result: ListResultDtoOfTreeNodeListDto) => {
            this.treeData = this._arrayToTreeConverterService.dataToNode(result.items, this.treeMappings);
        });
    }

    onNodeSelect(event) {}

    onNodeExpand(event) {
        if (event.node) {
            this._treeService.getChildren(event.node.code).subscribe(result => {
                event.node.children = this._arrayToTreeConverterService.dataToNode(result.items, this.treeMappings);
            });
        }
    }
}
